<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .item {
        float: left;
        width: 100px;
        height: 50px;
        border: 1px solid green;
        margin-left: 20px;
    }
</style>

<body>
    <div class="container">
        <h2 class="page-header">点击切换颜色</h2>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
    <script>

        //绑定div元素对象
        var items = document.getElementsByClassName("item");

        //遍历并绑定事件

        for (let i = 0; i < items.length; i++) {
            items[i].setAttribute("str", "#99f");
            items[i].onclick = function (){
                if(this.getAttribute("str") != "#99f") {
                    this.style.backgroundColor = "#99f";
                    this.setAttribute("str", "#99f");
                } else {
                    this.style.backgroundColor = "yellow";
                    this.setAttribute("str", "yellow");
                }
            }
        }

    </script>
</body>

</html>